﻿# dataclass转json
from typing import List
from dataclasses import dataclass, asdict, field
from json import dumps

@dataclass
class Students:
    id: int
    name: str

    @property
    def __dict__(self):
        return asdict(self)

    @property
    def json(self):
        return dumps(self.__dict__)

test_object_1 = Students(id=1, name="Kelvin")
print(test_object_1.json)


# json转dataclass
#方式一，通过三方库dataclasses-json
import dataclasses
import dataclasses_json

@dataclasses_json.dataclass_json
@dataclasses.dataclass
class Address:
    station: str
    street: str

@dataclasses_json.dataclass_json
@dataclasses.dataclass
class Person:
    name: str
    age: int
    address: Address

p = Person(name='chaos', age=100, address=Address('china', 'street 100'))
js = p.to_json()
print(p.to_json())
p2 = Person.from_json(js)
print(p2)
# 输出
{"name": "chaos", "age": 100, "address": {"state": "china", "street": "street 100"}}
Person(name='chaos', age=100, address=Address(state='china', street='street 100'))

#方式二，先用json.loads()转成字典，再实例化成dataclass，利用__post_init__解决嵌套对象问题
import json
import dataclasses

@dataclasses.dataclass
class mySubClass:
  sub_item1: str
  sub_item2: str

@dataclasses.dataclass
class myClass:
  item1: str
  item2: mySubClass

  # We need a __post_init__ method here because otherwise
  # item2 will contain a python dictionary, rather than
  # an instance of mySubClass.
  def __post_init__(self):
      self.item2 = mySubClass(**self.item2)


sampleData = '''
{
  "item1": "This is a test",
  "item2": {
    "sub_item1": "foo",
    "sub_item2": "bar"
  }
}
'''

myvar = myClass(**json.loads(sampleData))
myvar.item2.sub_item1 = 'modified'
print(json.dumps(dataclasses.asdict(myvar)))
